package leetcode.editor.cn;

//[8]字符串转换整数 (atoi)
public class StringToIntegerAtoi8 {
    public static void main(String[] args) {
        Solution solution = new StringToIntegerAtoi8().new Solution();

        int i = solution.myAtoi(" ");
        System.out.println("StringToIntegerAtoi8:main:" + i);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        //1 trim
        //2 + - 最后 * 1 、-1
        //3 char valid 0-9.
        //4 max min 边界判断
        //5 res = res*10 + cur
        //6 res * sign
        public int myAtoi(String s) {
            if (s == null || s.length() < 1) return 0;

            int index = 0;
            int sign = 1;// + -
            int total = 0;

            char[] chars = s.toCharArray();
            //del ' '
            while (index < chars.length && chars[index] == ' ') {
                index++;
            }

            //+ -
            if (index < chars.length) {
                if ('-' == chars[index]) {
                    sign = -1;
                    index++;
                } else if ('+' == chars[index]) {
                    sign = 1;
                    index++;
                }
            }

            //char -> int
            while (index < chars.length) {
                int cur = chars[index] - '0';
                if (cur > 9 || cur < 0) break;

                //边界判断
                if (sign == 1) {
                    if (total > Integer.MAX_VALUE / 10 || (total == Integer.MAX_VALUE / 10 && Integer.MAX_VALUE % 10 < cur)) return Integer.MAX_VALUE;
                } else {
                    if (-total < Integer.MIN_VALUE / 10 || (-total == Integer.MIN_VALUE / 10 && Integer.MIN_VALUE % 10 > -cur)) return Integer.MIN_VALUE;
                }

                total = total * 10 + cur;
                index++;
            }

            //total + -
            return total * sign;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}